package chat

import (
	"encoding/json"
	"errors"
	"time"

	netpack "im/im_server/proto"
	"strconv"

	"google.golang.org/protobuf/proto"
)

type JoinRoomMessageLogic struct {
	chatServer *ChatServer
	redisCmd   *RedisCmd
}

func (ch *JoinRoomMessageLogic) JoinChatRoomProcess(csJoinChatRoom *netpack.CSJoinChatRoom, c *Connection) error {
	dbChatRoomData, err := ch.redisCmd.HGetedisRoomValue(ctx,
		ServerID+HashKeyRoomIdStr+strconv.FormatInt(csJoinChatRoom.RoomId, 10), ServerID+HashfiledRoomIdStr)
	if err != nil {
		return err
	}

	dbPlayerChatRoom := &netpack.DBPlayerChatRoom{
		RoomId: csJoinChatRoom.RoomId,
	}

	jsonPlayerChatRoomData, err := json.Marshal(dbPlayerChatRoom)
	if err != nil {
		return err
	}

	dbChatRoomMember := &netpack.DBChatRoomMember{
		JoinChatRoomTime:    time.Now().Unix(),
		JoinChatRoomTimeStr: time.Now().Format("2006-01-02 15:04:05"),
		PlayerId:            c.player.PlayerId,
		MemberInfo:          "",
	}

	jsonChatRoomMemberData, err := json.Marshal(dbChatRoomMember)
	if err != nil {
		return err
	}

	err = ch.redisCmd.TxPipielineRedisJoinRoomValue(ctx,
		ServerID+SetKeyRoomIdStr+strconv.FormatInt(csJoinChatRoom.RoomId, 10), string(jsonChatRoomMemberData), // sadd
		ServerID+SetKeyPlayerIdStr+strconv.FormatInt(c.player.PlayerId, 10), string(jsonPlayerChatRoomData)) // sadd)
	if err != nil {
		return err
	}

	// 获取聊天室成员列表
	dbChatRoomMemberList, err := ch.redisCmd.SMembersRedisRoomMemberListValue(ctx,
		ServerID+SetKeyRoomIdStr+strconv.FormatInt(csJoinChatRoom.RoomId, 10))
	if err != nil {
		return err
	}

	if dbChatRoomMemberList == nil {
		scJoinChatRoom := &netpack.SCJoinChatRoom{
			Error: netpack.ErrCode_CHAT_ROOM_NO_EXIST,
		}
		return c.reply(netpack.MessageID_SC_JOIN_CHATROOM, scJoinChatRoom)
	}

	scJoinChatRoom := &netpack.SCJoinChatRoom{
		Error:        netpack.ErrCode_SUCCESS,
		ChatRoomInfo: dbChatRoomData,
		RoomMembers:  dbChatRoomMemberList,
	}

	err = c.reply(netpack.MessageID_SC_JOIN_CHATROOM, scJoinChatRoom)
	if err != nil {
		return err
	}

	return ChatRoomBroadcastChatMsg(ctx, ch.redisCmd, ch.chatServer,
		c.player.PlayerId, "join_room_test", csJoinChatRoom.RoomId, netpack.RoomChannel_CHAT_ROOM, dbChatRoomMemberList)
}

func (ch *JoinRoomMessageLogic) JoinChatRoom(msg proto.Message, c *Connection) error {
	csJoinChatRoom, ok := msg.(*netpack.CSJoinChatRoom)
	if !ok {
		return errors.New("parse join_chat_room message error")
	}
	return ch.JoinChatRoomProcess(csJoinChatRoom, c)
}
